package com.luna.dao;

import com.luna.beans.Message;
import com.luna.beans.ShowMessage;
import com.luna.utils.JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {

    public List<Message> selectMessagesByUserId(int user_id) throws SQLException {
        List<Message> list = new ArrayList<Message>();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from message where user_id=? and is_read=0";
        try {
            con = JDBC.getConnection();
            ps = con.prepareStatement(sql);
            ps.setInt(1, user_id);
            rs = ps.executeQuery();
            while (rs.next()) {
                list.add(new Message(
                    rs.getInt("id"),
                    rs.getInt("book_id"),
                    rs.getInt("user_id")
                ));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBC.close(rs, ps, con);
        }
        return list;
    }

    public List<ShowMessage> getShowMessage(List<Message> msgList) throws SQLException {
        List<ShowMessage> list = new ArrayList<ShowMessage>();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JDBC.getConnection();
            for (Message msg: msgList) {
                ShowMessage showMessage = new ShowMessage("");
                String sql = "select name from book where id=?";
                ps = con.prepareStatement(sql);
                ps.setInt(1, msg.getBook_id());
                rs = ps.executeQuery();
                if (rs.next())
                    showMessage.setBook(rs.getString("name"));

                list.add(showMessage);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBC.close(rs, ps, con);
        }
        return list;
    }

    public void readMessage(int user_id) throws Exception {
        Connection con = null;
        PreparedStatement ps = null;
        String sql = "update message set is_read=1 where user_id=?";
        try {
            con = JDBC.getConnection();
            ps = con.prepareStatement(sql);
            ps.setInt(1, user_id);
            ps.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBC.close(null, ps, con);
        }
    }
}
